package org.simplextensions.ui.view;

import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.ui.IApplicationWindow;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 
 * 
 * @author Tomasz Krzyzak, <a
 *         href="mailto:tomasz.krzyzak@gmail.com">tomasz.krzyzak@gmail.com</a>
 * @since 2010-05-20 15:10:24
 */
public abstract class ViewManager<T extends IViewRegion> {

	private final IExtensionRegistry extensionRegistry;
	private ViewExtensionPoint vep;

	public ViewManager(IApplicationWindow applicationWindow) {
		this(applicationWindow.getExtensionRegistry());
	}

	public ViewManager(IExtensionRegistry extensionRegistry) {
		this.extensionRegistry = extensionRegistry;

		this.vep = extensionRegistry.getExtensionPoint(ViewExtensionPoint.class);
	}

	private List<IView<T>> addedViews = new LinkedList<IView<T>>();
	private List<IView<T>> initializedViews = new LinkedList<IView<T>>();

	protected List<IView<T>> getViews(){
		return Collections.unmodifiableList(addedViews);
	}
	
	public void addView(IView<T> view) {
		if (!addedViews.contains(view)) {
			view.init(createViewRegion());
			addedViews.add(view);
		}
	}

	public void removeView(IView<T> iView) {
		if (iView != null && addedViews.contains(iView)) {
			addedViews.remove(iView);
			initializedViews.remove(iView);

			removeViewRegion(iView.getViewRegion());
			iView.dispose();
		}
	}

	public void activateView(IView<T> iView) {
		if (iView != null) {
			if (!initializedViews.contains(iView)) {
				iView.createContents();
				initializedViews.add(iView);
			}
			activateViewRegion(iView.getViewRegion());
			iView.setFocus();
		}
	}

	public IExtensionRegistry getExtensionRegistry() {
		return extensionRegistry;
	}

	public void createContent() {
		boolean activated = false;
		for (IView<?> view : this.vep.getViews()) {
			addView((IView<T>) view);
			if (!activated) {
				activateView((IView<T>) view);
				activated = true;
			}
		}

	}
	
	protected abstract void activateViewRegion(T viewRegion);

	protected abstract void removeViewRegion(T viewRegion);

	protected abstract T createViewRegion();

}
